# from itsdangerous import JSONWebSignatureSerializer as JSONSerializer
from flask_httpauth import HTTPTokenAuth
import string, random, jwt
from flask import request, current_app
from lib.db import accessor

auth = HTTPTokenAuth()
class JWT():
    __slots__ = ()
    __lib_hta = __import__('flask_httpauth', fromlist=['HTTPTokenAuth'])
    auth = __lib_hta.HTTPTokenAuth()
    
    @classmethod
    def generate(cls, **kwargs):
        return jwt.encode({'data': kwargs}, current_app.config['SECRET_KEY'], algorithm="HS256")

    @auth.verify_token
    def verifyToken(self):
        try:
            header = request.headers
            if 'token' not in header: return False
            data = jwt.decode(header['token'], current_app.config['SECRET_KEY'], algorithms=["HS256"])
            if data and 'id' in data['data']: 
                ok, _, res = accessor.select('t_user', 'is_active', {'id': data['data']['id']})
                if ok and len(res) > 0: return res[0]['is_active'] > 0
            return False
        except Exception:
            return False

    @classmethod
    def idGenerator(cls, size=128, chars=string.ascii_letters + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))

